﻿CREATE PROCEDURE [dbo].[EmailQueue_Post]
	@templateName NVARCHAR(256),

	@beginSentDate DATETIME,

	@recipient nvarchar(max),
	@bccRecipient nvarchar(max) = NULL,

	@parameters nvarchar(max),

	@parameterDelimiter nvarchar(8) = '###',
	@pairDelimiter nvarchar(8) = '##'

AS
BEGIN
	
	-------------- EMAIL TEMPLATE-------------------
	DECLARE @subject nvarchar(256)
	DECLARE @body nvarchar(max)
	DECLARE @isHtml BIT

	SELECT @subject = CAST(dbo.UpdateStringParameters(Subject, @parameters, '#', @parameterDelimiter, @pairDelimiter) AS NVARCHAR(256)), 
					@body = dbo.UpdateStringParameters(Body, @parameters, '#', @parameterDelimiter, @pairDelimiter), 
					@isHtml = IsHtml
	FROM [dbo].[email_Template]
	WHERE [Name] = @templateName AND [Enabled] = 1

	IF @subject IS NULL OR @body IS NULL OR @isHtml IS NULL 
	BEGIN
		RETURN
	END

	-------------- EMAIL QUEUE --------------------


	INSERT INTO [dbo].[email_Queue]
							([Recipient]
							,[BccRecipient]
							,[Subject]
							,[Body]
							,[IsHtml]
							,[BeginSentDate]
							,[CreateDate]
							,[RequestDate]
							,[SendDate]
							,[ErrorDate]
							,[ErrorCount]
							,[ErrorText])
    VALUES
          (@recipient				--<Recipient, nvarchar(max),>
          ,@bccRecipient		--<BccRecipient, nvarchar(max),>
          ,@subject					--<Subject, nvarchar(256),>
          ,@body						--<Body, nvarchar(256),>
					,@isHtml					--bit
          ,@beginSentDate		--<BeginSentDate, datetime,>
          ,GETDATE()				--<CreateDate, datetime,>
          ,NULL							--<RequestDate, datetime,>
          ,NULL							--<SendDate, datetime,>
          ,NULL							--<ErrorDate, datetime,>
          ,0								--<ErrorCount, int,>
          ,NULL							--<ErrorText, nvarchar(max),>
					)

	SELECT @beginSentDate AS BeginSentDate

END